const jwt = require('jsonwebtoken') //token: `Bearer ${jwt.sign({username: userInfo.username}, secretKey, {expiresIn: '10h'})}`
const secretKey = "yangzhitao ^_^"  //密钥
const express = require("express")

const router = express.Router()
const db = require("../../Database")





//注册
router.post("/register", async (request, response) => {
    const userInfo = await new Promise( (resolve, reject) => {
        request.on("data", (data) => {
            if (JSON.parse(data.toString())) resolve(JSON.parse(data.toString()))
            else reject(false)
        })
    })
    if (!userInfo) return response.send({code: 250, message: "服务器故障"})
    try {
        const flag = await new Promise( (resolve, reject) => {
            db.query("select * from users where username = ?", userInfo.username, (err, result) => {
                if (err) return console.log(err.message)
                if (result.length > 0) reject(false)
                else resolve(true)
            })
        })
        if (flag) {
            db.query("insert into users (username, password, text, likes, collection, concern) values (?,?,?,?,?,?)", [userInfo.username, userInfo.password, "", "[]", "[]", "[]"], (err, result) => {
                if (err) return console.log(err.message)
                if (result.affectedRows === 1) {
                    response.send({
                        code: 200,
                        message: "账号注册成功",
                        userInfo: {...userInfo, id: result.insertId, text: "", pic: 'http://127.0.0.1:8080/public/default.jpg', name: "未设置姓名", age: 22, birthday: "", likes: "[]" , collection: "[]", concern: "[]"},
                        token: `Bearer ${jwt.sign({...userInfo, concern: "[]", id: result.insertId, text: "", pic: 'http://127.0.0.1:8080/public/default.jpg', name: "未设置姓名", age: 22, birthday: "", likes: "[]" , collection: "[]"}, secretKey, {expiresIn: '10h'})}`
                    })
                }
            })
        }
    } catch (e) {
        return response.send({code: 250, message: "已存在该用户！"})
    }
})
//登录
router.post("/login", async (request, response) => {

    const userInfo = await new Promise( (resolve, reject) => {
        request.on("data", (data) => {
            if (JSON.parse(data.toString())) resolve(JSON.parse(data.toString()))
        })
    })
    db.query("select * from users where username = ?", userInfo.username, (err, result) => {
        if (err) return console.log(err.message)
        if (result.length === 0) return response.send({code: 250, message: "该用户名未注册，请先注册一下吧"})
        if (result[0].password !== userInfo.password) return response.send({code: 250, message: "密码错误，请重新输入吧"})
        else return response.send({code: 200, message: "欢迎使用本网站", userInfo: result[0], token: `Bearer ${jwt.sign(result[0], secretKey, {expiresIn: '10h'})}`})
    })
})
//获取视频
router.get("/get_video", (request, response) => {
    db.query("select * from videos", (err, result) => {
        if (err) return console.log(err.message)
        response.send({code: 200, message: "获取成功", data: result})
    })
})
//通过id获取视频
router.get("/get_video_by_id", async (request, response) => {
    const data = await new Promise( (resolve, reject) => {
        db.query("select * from videos where id = ?", [request.query.id], (err, result) => {
            if (err) return console.log(err.message)
            resolve(result[0])
        })
    })
    db.query("select * from users where username = ?", data.username, (err, result) => {

        if (err) return console.log(err.message)
        data.userInfo = result[0]
        response.send({ code: 200, message: "查询成功", data: data})
    })
})
//添加视频播放量
router.get("/change_watch_count", async (request, response) => {
    const watch_count = await new Promise((resolve, reject) => {
        db.query("select * from videos where id = ?", request.query.id, (err, result) => {
            if (err) return console.log(err.message)
            resolve(result[0].watch_count)
        })
    })
    db.query("update videos set watch_count = ? where id = ?", [watch_count + 1, parseInt(request.query.id)], (err, result) => {
        if (err) return console.log(err.message)
        if (result.affectedRows === 1) return response.send({code: 200, message: "添加视频播放量成功"})
    })
})
//获取视频评论
router.get("/get_comments", (request, response) => {
    db.query("select * from comments where video_id = ?", request.query.id, (err, result) => {
        if (err) return console.log(err.message)
        response.send({code: 200, message: "获取视频评论成功", data: result})
    })
})
//获取指定用户的视频
router.get("/get_video_by_username", async (request, response) => {
    const data = await new Promise( (resolve, reject) => {
        db.query("select * from videos where username = ?", request.query.username, (err, result) => {
            if (err) return console.log(err.message)
            resolve(result)
        })
    })
    response.send({code: 200, message: "获取成功", data})
})
//模糊搜索
router.get("/obscure_search", (request, response) => {

    db.query(`SELECT * FROM videos where title like '%${request.query.key}%'`, (err, result) => {
        if (err) return console.log(err.message)
        response.send({code: 200, message: "查询成功", data: result})
    })
})
//推荐，播放量前10的视频
router.get("/recommend", (request, response) => {
    db.query("select * from enjoy_time.videos  order by watch_count desc  limit 0,10", (err, result) => {
        if (err) return console.log(err.message)
        response.send({code: 200, message: "查询成功", data: result})
    })
})
//获取用户信息(指定Id)
router.get("/get_userInfo", (request, response) => {
    db.query("select * from users where id = ?", request.query.id, (err, result) => {
        if (err) return console.log(err.message)
        if (result.length > 0) return response.send({code: 200, message: "查询成功", data: result[0]})
    })
})
//获取后面的视频
router.get("/get_affter_video", async (request, response) => {
    const video = await new Promise( (resolve, reject) => {
        db.query("select * from enjoy_time.videos where id > ? limit 0,1", request.query.id, (err, result) => {
            if (err) return console.log(err.message)
            if (result.length > 0) return resolve(result[0])
            // if (result.length > 0) return response.send({code: 200, message: "获取成功", data: result[0]})
            else return response.send({code: 250, message: "已到达最后一个视频"})
        })
    })
    db.query("select * from users where username = ?", video.username, (err, result) => {
        if (err) return console.log(err.message)
        video.userInfo = result[0]
        if (result.length > 0) return response.send({code: 200, message: "获取成功", data: video})
    })
})
//获取前面的视频
router.get("/get_before_video", async (request, response) => {
    const video = await new Promise( (resolve, reject) => {
        db.query("select * from enjoy_time.videos where id < ? limit 0,1", request.query.id, (err, result) => {
            if (err) return console.log(err.message)
            if (result.length > 0) resolve(result[0])
            else return response.send({code: 250, message: "已到达第一个视频"})
        })
    })
    db.query("select * from users where username = ?", video.username, (err, result) => {
        if (err) return console.log(err.message)
        video.userInfo = result[0]
        response.send({code: 200, message: "获取成功", data: video})
    })
})


//sse连接
router.get('/sse', (request, response) => {
    response.setHeader('Content-Type', 'text/event-stream')
    response.setHeader('Cache-Control', 'no-cache')
    response.setHeader('Connection', 'keep-alive')

    setInterval(() => {
        response.write('data: 你好\n\n')
    }, 1000)
})
module.exports = router